package com.servlet;

import com.entity.News;
import com.service.NewService;
import com.service.impl.NewsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@WebServlet("/news.let")
public class NewsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.设置编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //2.获取各种对象
        PrintWriter out = resp.getWriter();
        HttpSession session = req.getSession();
        NewService newService = new NewsServiceImpl();
        String type = req.getParameter("type");
        switch (type){
            case "listNews":
                if (session.getAttribute("user") == null) {
                    out.println("<script>alert('请登录');parent.window.location.href='home-1.jsp';</script>");
                    return;
                }
                int pageSize=6;
                int pageIndex = Integer.parseInt( req.getParameter("pageIndex"));
                int pageCount = newService.getPageCount(pageSize);
                if(pageIndex<1){
                    pageIndex=1;
                }
                if(pageIndex>pageCount){
                    pageIndex=pageCount;
                }
                List<News> newsList = newService.selectDate(pageIndex,pageSize);
                List<News> recentPosts = newService.recentPosts();
                req.setAttribute("recentPosts",recentPosts);
                req.setAttribute("news",newsList);
                req.setAttribute("pageCount",pageCount);
                req.getRequestDispatcher("blog.jsp?pageIndex="+pageIndex).forward(req,resp);
                break;
            case "blogDetails":
                Integer id =Integer.parseInt(req.getParameter("id"));
//                int commentPageIndex=Integer.parseInt(req.getParameter("pageIndex"));
                News details = newService.blogDetails(id);
//                List<Map<String,Object>> blogComment=newService.getComment(id);
                req.setAttribute("details",details);
                req.getRequestDispatcher("blog-details.jsp").forward(req,resp);
                break;
        }
    }
}
